<?php
/**
 * Created by PhpStorm.
 * User: wuchao
 * Date: 2020/6/8
 * Time: 14:06
 */

namespace app\api\controller\v1\balance;

use app\api\model\DeliveryControModel;
use think\facade\Db;
use app\middleware\BackAuth;
use think\facade\Validate;
use think\Request;
use think\response\Json;
use think\validate\ValidateRule;

/*
 * 采购员、配送员、分拣员、库管员管理控制器*/

class DeliveryContro
{
    protected $middleware = [BackAuth::class];

    /**
     * 获取所有已出库或者发货的订单
     * @param Request $request
     * @return Json
     */
    public function get_out_order(Request $request)
    {
        // 获取参数
        $input['status'] = $request->post('status');
        $input['driver_id'] = $request->post('driver_id');
        $input['center_id'] = $request->post('center_id');
        // 参数校验
        $validate = Validate::rule([
            'status' => ValidateRule::isRequire(null, '缺少参数'),
            'driver_id' => ValidateRule::isRequire(null, '缺少参数'),
            'center_id' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        return DeliveryControModel::get_out_order($input);
    }

    /**
     * 订单发货
     * @param Request $request
     * @return mixed
     */
    public function order_send(Request $request)
    {
        try {
            Db::startTrans();
            $driver_id = $request->param('driver_id');//发货人ID
            $order_id = $request->param('order_id');//订单ID
            if (empty($driver_id) || empty($order_id)) return jsonFail('缺少参数');
            $order_ids = explode(',', $order_id);
            if (empty($order_ids)) return jsonFail('缺少参数');
            $role = Db::table('admin')->alias('a')
                ->where('a.id', $driver_id)
                ->join('role b ', 'a.role_id= b.id')
                ->field('a.name,a.phone,b.name as role_type')
                ->find();
            if (empty($role)) return jsonFail('系统角色错误');
            $res = Db::table('order')->where('id', 'in', $order_id)->update(['status' => 2, 'send_time' => time()]);//主订单都已发货
            foreach ($order_ids as $v) {
                $red = Db::table('order_status')->insertGetId([
                    'oid' => $v,
                    'change_message' => '已发货, 发货人ID：' . $driver_id . '， 发货人姓名：' . $role['name'] . '，发货人电话：' . $role['phone'],
                    'name' => $role['name'],
                    'phone' => $role['phone'],
                    'role_type' => $role['role_type'],
                    'create_time' => time(),
                ]);
            }
            if ($res != 0 && $red != 0) {
                Db::commit();
                return jsonSuccess('发货成功');
            } else {
                Db::rollback();
                return jsonFail('发货失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }
    }

    /**
     * 订单确认送达
     * @param Request $request
     * @return mixed
     */
    public function order_arrive(Request $request)
    {
        try {
            Db::startTrans();
            $driver_id = $request->param('driver_id');//发货人ID
            $order_id = $request->param('order_id');//订单ID
            if (empty($driver_id) || empty($order_id)) return jsonFail('缺少参数');
            $order_ids = explode(',', $order_id);
            if (empty($order_ids)) return jsonFail('缺少参数');
            $role = Db::table('admin')->alias('a')
                ->where('a.id', $driver_id)
                ->join('role b ', 'a.role_id= b.id')
                ->field('a.name,a.phone,b.name as role_type')
                ->find();
            if (empty($role)) return jsonFail('系统角色错误');
            $res = Db::table('order')->where('id', 'in', $order_id)->update(['status' => 3, 'arrive_time' => time(), 'driver_id' => $driver_id]);//主订单都已发货
            foreach ($order_ids as $v) {
                $red = Db::table('order_status')->insertGetId([
                    'oid' => $v,
                    'change_message' => '商品已送达, 送货人ID：' . $driver_id . '， 送货人姓名：' . $role['name'] . '，送货人电话：' . $role['phone'],
                    'name' => $role['name'],
                    'phone' => $role['phone'],
                    'role_type' => $role['role_type'],
                    'create_time' => time(),
                ]);
            }
            if ($res != 0 && $red != 0) {
                Db::commit();
                return jsonSuccess('发货成功');
            } else {
                Db::rollback();
                return jsonFail('发货失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }

    }

    /**
     * 获取确认已送达的订单
     * @param Request $request
     * @return mixed
     */
    public function all_deliver(Request $request)
    {
        $center_id = $request->param('center_id');
        if (empty($center_id)) return jsonFail('center_id不能为空！');
        $data = Db::table('order')->where('center_id', $center_id)->where('status', '>=', 3)->select()->toArray();
        foreach ($data as $key => &$value) {
            if (!empty($value['retrieval_id'])) {
                $value['retrieval_info'] = Db::table('admin')->where('id', $value['retrieval_id'])->field('phone,name')->find();
            }
            if (!empty($value['driver_id'])) {
                $value['driver_info'] = Db::table('admin')->where('id', $value['retrieval_id'])->field('phone,name')->find();
            }
            $value['sort_center_info'] = Db::table('organization')->where('id', $center_id)->find();
            $value['user_info'] = Db::table('company_address')->where('id', $value['address_id'])->field('name,phone,province,city,area,address')->find();
        }
        return jsonSuccess('获取成功', ['list' => $data]);
    }

    /**
     * 获取配送地址表
     * @param Request $request
     * @return mixed
     */
    public function Distribution_route(Request $request)
    {
        $driver_id = $request->param('driver_id');//发货人ID
        $center_id = $request->param('center_id');
        $type = $request->param('type', 'asc');
        if (empty($center_id) || empty($driver_id)) return jsonFail('缺少参数');
        $group_ids = array_column(Db::table('company_center')->where('center_id', $center_id)->field('group_id')->select()->toArray(), 'group_id');
        $order = Db::table('order')->where('center_id', $center_id)->where('driver_id', $driver_id)->where('is_pay', 1)->where('status', 'in', [0, 1, 2])->field('group_id')->select()->toArray();
        $order_groups = array_column($order, 'group_id');
        $driver_route = Db::table('driver_route')->alias('a')
            ->join('company b ', 'a.move_id= b.id')
            ->where('a.driver_id', $driver_id)
            ->where('move_id', 'in', $group_ids)
            ->where('a.type', 2)->order('a.sort', $type)->field('a.id,a.move_id,a.is_arrive,b.name')->select()->toArray();
        $dir_groups = array_column($driver_route, 'move_id');
        $outData = [];
        $result = array_intersect($dir_groups, $order_groups);

        foreach ($driver_route as $key => &$value) {
            if (key_exists($key, $result)) {
                if ($value['move_id'] == $result[$key]) {
                    $value['is_show'] = 1;
                } else {
                    $value['is_show'] = 0;
                }
            } else {
                $value['is_show'] = 0;
            }
        }
        return jsonSuccess('获取成功', $driver_route);
    }

    /**
     * 调整配送路线顺序
     * @param Request $request
     * @return mixed
     */
    public function Adjustment_route(Request $request)
    {
        $driver_id = $request->param('driver_id');//发货人ID
        $data = $request->param('data');//调整过后的顺序
        $datas = json_decode($data, true);
        if (empty($driver_id) || empty($data)) return jsonFail('缺少参数');
        try {
            $datas = json_decode($data, true);
            Db::startTrans();
            foreach ($datas as $v) {
                $res = Db::table('driver_route')->where('id', $v['id'])->update(['sort' => $v['sort']]);
            }
            Db::commit();
            return jsonSuccess('调整成功');
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }
    }

    /**
     * 司机获取所配送的分拣中心以及订单数量
     * @param Request $request
     * @return mixed
     */
    public function DeliveryBalance(Request $request)
    {
        $driver_id = $request->param('driver_id');//司机ID
        $type = $request->param('type', 1);
        if (empty($driver_id)) return jsonFail('缺少参数');
        $company = Db::table('company')->where('driver_id', $driver_id)->field('id')->select()->toArray();
        $group_ids = array_column($company, 'id');
        $center_group = Db::table('company_center')->where('group_id', 'in', $group_ids)->field('center_id')->select()->toArray();
        $center_ids = array_column($center_group, 'center_id');
        $data = Db::table('organization')
            ->where('id', 'in', $center_ids)
            ->field('id,name')->select()->toArray();
        if ($type == 1) {
            foreach ($data as $key => $v) {
                $data[$key]['num'] = Db::table('order')->where('is_pay', 1)->where('status', 1)->where('center_id', $v['id'])->where('driver_id', $driver_id)->count();
                $data[$key]['order_ids'] = array_column(Db::table('order')->where('is_pay', 1)->where('status', 1)->where('center_id', $v['id'])->where('driver_id', $driver_id)->field('id')->select()->toArray(), 'id');
            }
        }
        return jsonSuccess('获取成功', $data);
    }

    /**
     * 司机获取司机列表
     * @param Request $request
     * @return mixed
     */
    public function DriverList(Request $request)
    {
        $driver_id = $request->param('driver_id');//司机ID
        if (empty($driver_id)) return jsonFail('缺少参数');
        $role_id = Db::table('admin')->where('id', $driver_id)->value('role_id');
        $data = Db::table('admin')->where('id', '<>', $driver_id)->where('role_id', $role_id)->field('id,name,phone')->select()->toArray();
        return jsonSuccess('获取成功', $data);
    }

    /**
     * 司机委派订单
     * @param Request $request
     * @return mixed
     */
    public function DriverEntrust(Request $request)
    {
        $entrust_id = $request->param('entrust_id');//委托司机ID
        $driver_id = $request->param('driver_id');//跑路司机ID
        $order_id = $request->param('order_ids');//订单IDs
        if (empty($entrust_id) || empty($driver_id) || empty($order_id)) return jsonFail('缺少参数');
        $entrust_info = Db::table('admin')->where('id', $entrust_id)->field('id,name,phone')->find();
        $driver_info = Db::table('admin')->where('id', $driver_id)->field('id,name,phone')->find();
        $order_ids = explode(',', $order_id);
        try {
            Db::startTrans();
            $res = Db::table('order')->where('id', 'in', $order_ids)->where('is_pay', 1)->where('status', 1)->update(['entrust_id' => $entrust_id, 'driver_id' => $driver_id]);
            foreach ($order_ids as $v) {
                $red = Db::table('order_status')->insertGetId([
                    'oid' => $v,
                    'change_message' => '订单已被委派，派送人姓名：' . $driver_info['name'] . ' ,派送人电话：' . $driver_info['phone'],
                    'name' => $entrust_info['name'],
                    'phone' => $entrust_info['phone'],
                    'role_type' => '配送员',
                    'create_time' => time(),
                ]);
            }
            if ($red != 0 && $res != 0) {
                DB::commit();
                return jsonSuccess('委派成功');
            } else {
                Db::rollback();
                return jsonFail('委派失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }

    }

    /*
     * 判断子订单是否全部发货
     * @param int $id
     * @return boolean
     * */
    public function select_type($order)
    {
        $temp = 0;
        foreach ($order as $key => $value) {
            if ($temp == 0) {
                $temp = $value['status'];
            } else {
                if ($temp != $value['status']) {
                    return false;
                }
            }
        }
        return true;
    }
}